#include "unixhead.h"

#include <string>
#include <vector>

#include <workflow/WFFacilities.h>
#include <workflow/RedisMessage.h>

#include <iostream>
using namespace std;

static WFFacilities::WaitGroup waitGroup(1);

void sighandler(int signum)
{
    (void)signum;
    cout << "wait group done\n";
    waitGroup.done();
}

int main()
{
    signal(SIGINT, sighandler);
    int * pnumber = new int(100);
    cout << "main number:" << pnumber << endl;
    cout << "main &number:" << pnumber << endl;

    auto redisTask = WFTaskFactory::create_redis_task(
        "redis://127.0.0.1:6379", 0, [=](WFRedisTask * redisTask){
        cout << "\nredisTask callback is running\n";
        cout << "callback pnumber:" << pnumber << endl;
        cout << "callback *pnumber:" << *pnumber << endl;

        auto req = redisTask->get_req();
        auto resp = redisTask->get_resp();
        int state = redisTask->get_state();
        int error = redisTask->get_error();
        protocol::RedisValue value;
        switch(state){
        case WFT_STATE_SYS_ERROR:
            fprintf(stderr, "system error: %s\n", strerror(error)); break;
        case WFT_STATE_DNS_ERROR:
            fprintf(stderr, "dns error: %s\n", gai_strerror(error)); break;
        case WFT_STATE_SUCCESS:
            resp->get_result(value);
            if(value.is_error()) {
                fprintf(stderr, "redis error\n");
                state = WFT_STATE_TASK_ERROR;
            }
            break;
        }

        if(state != WFT_STATE_SUCCESS) {
            printf("error occurs\n");
            return;
        }

        //遍历RedisRequest
        string cmd;
        vector<string> params;
        req->get_command(cmd);
        req->get_params(params);
        cout << "redis command: " << cmd << " ";
        for(auto & param : params) {
            cout << param << " ";
        }
        cout << endl;

        //遍历RedisResponse
        if(value.is_string()) {
            cout << "value is a string, value: " 
                 << value.string_value() << endl;
        } else if(value.is_array()) {
            cout << "value is a array" << endl;
            for(size_t idx = 0; idx < value.arr_size(); ++idx) {
                cout << "arr[" << idx << "]:"
                     << value.arr_at(idx).string_value() << endl;
            }
        } else if(value.is_int()) {
            cout << "value is a int number: " << value.int_value() << endl;
        }
    });
    auto req = redisTask->get_req();
    //设置任务的属性
    string cmd("HSET");
    vector<string> params{"student", "name", "liubei", "age", "48"};
    req->set_request(cmd, params);
    //交给框架运行
    redisTask->start();//调用start方法之后，才会创建序列

    waitGroup.wait();//阻塞当前进程

    //回收资源
    delete pnumber;
    cout << "main func delete pnumber" << endl;
    return 0;
}
